/**
 *@desc
 *@author bie
 *@date [$]
 */
import React, { useCallback, useEffect, useState } from 'react';
import { Select, Spin } from 'antd';
import Icon from '@ant-design/icons';
import PropTypes from 'prop-types';
import useRequest from '../request';
import './select.less';
/**
 * 检查list中是否包含data，若不包含则加入data，默认返回list
 */
const { Option } = Select;
export const checkListHasData = (list, key, data = {}, filter = {}) => {
  let listTem = [];
  if (data[key]) {
    let isFound = false;
    // eslint-disable-next-line no-restricted-syntax
    for (const item of list) {
      if (item[key] === data[key]) {
        isFound = true;
        break;
      }
    }
    if (!isFound) {
      listTem = [...list, data];
    } else {
      listTem = list;
    }
  } else {
    listTem = list;
  }

  // 过滤
  let newList = [];
  if (filter.value) {
    // eslint-disable-next-line no-restricted-syntax
    for (const item of listTem) {
      if (filter.value === item[filter.key]) {
        newList.push(item);
      }
    }
  } else {
    newList = listTem;
  }
  return newList;
};

export const getOption = (name, key, list, disabledList = []) => {
  if (!list || list.length === 0) {
    return [];
  }
  return list.map((i) => {
    const querykey = i.namePinyin ? i.namePinyin + i.name : i.name; // 拼音搜索码
    return (
      <Option
        querykey={querykey}
        value={i[key]}
        key={i[key]}
        disabled={disabledList.indexOf(i[key]) > -1}
      >
        {i[name]}
      </Option>
    );
  });
};
let timer = null;
const SelectCustom = (props) => {
  const [valueCurrent, setValueCurrent] = useState(''); // 当前显示值
  const [optionListCurrent, setOptionListCurrent] = useState([]); // 当前显示列表数据
  const { loading, postData } = useRequest();

  const {
    extraObject = {},
    disabledList = [],
    onChange,
    value,
    optionList = [],
    searchUrl,
    allowSearch,
    keyValue = ['name', 'id'],
    ...args
  } = props;

  const triggerChange = useCallback(
    (valueTem) => {
      // Should provide an event to pass value to Form.
      if (onChange) {
        onChange(valueTem);
      }
    },
    [onChange],
  );

  const onSelectSearch = useCallback(
    (valueTem) => {
      setOptionListCurrent([]);
      if (onChange) {
        onChange(valueTem);
      }
      if (valueTem && searchUrl) {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          postData(searchUrl, {
            data: {
              condition: { keyword: valueTem },
              pagingQuery: { pageIndex: 1, pageSize: 500 },
            },
          }).then((res) => {
            if (res && res.success) {
              const keys = props.keyValue || [];
              const optionListTem = [...res.models].map((i) => {
                return {
                  ...i,
                  label: i[keys[0]],
                  value: i[keys[1]],
                };
              });
              setOptionListCurrent(optionListTem);
            }
          });
        }, 800);
      }
    },
    [searchUrl, onChange],
  );

  // 监听 optionList
  useEffect(() => {
    setOptionListCurrent(optionList);
  }, [optionList]);

  // 监听 value 变化
  useEffect(() => {
    setValueCurrent(value);
  }, [value]);

  return (
    <span className="xuanyue-select">
      <Select
        showSearch
        allowClear
        // allowClear
        optionFilterProp="children"
        showArrow
        virtual
        onSearch={allowSearch ? onSelectSearch : null}
        // maxTagTextLength={4}<BulbOutlined />
        // maxTagCount={mode ? 2 : 0}
        notFoundContent={
          allowSearch ? (
            loading ? (
              <Spin size="small" />
            ) : (
              <Icon type="bulb" />
            )
          ) : null
        }
        style={{ width: '100%' }}
        placeholder="请选择"
        dropdownMatchSelectWidth
        getPopupContainer={(trigger) => trigger.parentNode}
        // optionFilterProp="querykey"
        filterOption={
          allowSearch
            ? false
            : (_input, option) => {
                if (_input) {
                  const curr =
                    (
                      option.props.querykey ||
                      option.props.children ||
                      ''
                    ).toLowerCase() || '';
                  const l = _input.length;
                  const s = curr.substr(0, l);
                  return s === _input || curr.includes(_input.toLowerCase());
                }
              }
        }
        {...args}
        value={valueCurrent}
        onChange={triggerChange}
      >
        {getOption(
          ...keyValue,
          checkListHasData(optionListCurrent, keyValue[1], extraObject),
          disabledList,
        )}
      </Select>
      {args.addonAfter}
    </span>
  );
};
/*
 * 关键附加参数，其余参数 请参考 antd select组件
 * */
SelectCustom.propTypes = {
  disabledList: PropTypes.array,
  optionList: PropTypes.array,
  value: PropTypes.string,
  extraObject: PropTypes.object,
  onChange: PropTypes.func,
  searchUrl: PropTypes.string,
  allowSearch: PropTypes.bool,
  keyValue: PropTypes.array,
};
export default React.memo(SelectCustom);
